module.exports = class extends think.Service {
  generateAuthCode() {
    return think.md5(think.uuid('v4'));
  }

  /**
   * 验证用户名和密码
   * @param {*} password
   * @param {*} savePassword
   */
  checkPassword(password, savePassword) {
    const { md5Password, salt } = this.splitSavePassword(savePassword);
    return this.generateMd5Password(password, salt) === md5Password;
  }

  splitSavePassword(savePassword) {
    const passwordSalt = {md5Password: '', salt: ''};

    if (think.isEmpty(savePassword) || savePassword.length !== 51) {
      return passwordSalt;
    }

    if (savePassword.indexOf('__thincho__') !== 32) {
      return passwordSalt;
    }

    const splitArray = savePassword.split('__thincho__');
    passwordSalt.md5Password = splitArray[0];
    passwordSalt.salt = splitArray[1];
    return passwordSalt;
  }

  /**
   * 生成8位密码盐字符串
   */
  generateSalt() {
    return think.uuid('v4').substring(0, 8);
  }

  /**
   * 根据密码和盐生成 md5 后的密码
   * @param {*} password
   * @param {*} salt
   */
  generateMd5Password(password, salt) {
    return think.md5(think.md5('thin' + password + 'cho') + 'thincho' + salt);
  }
};
